#!/bin/bash

set -e

# Configuration
BACKUP_DIR="./backups"
TIMESTAMP=$(date +%Y%m%d-%H%M%S)
BACKUP_NAME="baihu-backup-$TIMESTAMP"
MAX_BACKUPS=10

echo "💾 Creating backup: $BACKUP_NAME"

# Create backup directory
mkdir -p "$BACKUP_DIR"

# Create backup archive
tar -czf "$BACKUP_DIR/$BACKUP_NAME.tar.gz" \
    --exclude='node_modules' \
    --exclude='dist' \
    --exclude='*.log' \
    --exclude='.git' \
    data/ \
    .env \
    docker-compose.prod.yml \
    nginx.conf

echo "✅ Backup created: $BACKUP_DIR/$BACKUP_NAME.tar.gz"

# Clean up old backups
cd "$BACKUP_DIR"
ls -t *.tar.gz | tail -n +$((MAX_BACKUPS + 1)) | xargs -r rm -f
cd ..

echo "🧹 Cleaned up old backups (keeping $MAX_BACKUPS most recent)"
echo "📊 Available backups:"
ls -la "$BACKUP_DIR"/*.tar.gz 2>/dev/null || echo "No backups found"
